package com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.os.Handler
import android.text.Html
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.RecyclerViewScrollHelper
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.PaperPerAnalysisInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.ScoreSoundUtil
import com.lancoo.znbkxx.teacher.widget.CountNumberView
import com.lancoo.znbkxx.teacher.widget.HtmlTagHandler
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.*
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.BtnBack
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.BtnRefresh
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.GifLoading2
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.RvAnswerSheetParent
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.TvFullScore
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.TvMyScore
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.TvMyScoreRate
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.TvPaperName
import kotlinx.android.synthetic.main.aibk_activity_analysis_answersheet_1v1.TvUseTime
import org.koin.androidx.viewmodel.ext.android.viewModel


class AibkAnalysisAnswerSheetActivity_1v1 : KBaseActivity(), View.OnClickListener {

    private var stuId = ""
    private var paperId = ""
    private var paperName = ""
    companion object {
        fun launch(activity: Activity,stuId:String, paperId: String, paperName: String) {
            val intent = Intent(activity, AibkAnalysisAnswerSheetActivity_1v1::class.java)
            intent.putExtra("StuID", stuId)
            intent.putExtra("PaperID", paperId)
            intent.putExtra("PaperName", paperName)
            activity.startActivity(intent)
        }
    }

    private val mViewModel: MarkViewModel by viewModel()
    private var paperPerAnalysisInfor: PaperPerAnalysisInfor? = null
    private var scoreSoundUtil: ScoreSoundUtil? = null

    override fun setLayout(): Int {
        return R.layout.aibk_activity_analysis_answersheet_1v1
    }

    override fun initView() {
        BtnBack.setOnClickListener(this)
        BtnRefresh.setOnClickListener(this)
        TvPaperName.text = paperName+"的分析"

        //初始化短音频
        scoreSoundUtil = ScoreSoundUtil.getInstance(this)
        scoreSoundUtil!!.init()
    }

    override fun initData() {
        stuId = intent.getStringExtra("StuID")
        paperId = intent.getStringExtra("PaperID")
        paperName = intent.getStringExtra("PaperName")

        Handler().postDelayed({
            getpaperPerAnalysisInforAndRefresh()
        },500)
    }

    private fun getpaperPerAnalysisInforAndRefresh() {

        mViewModel.getPaperAnalysisInfor_1v1(paperId)
                .doOnSubscribe {
                    LlAnswerSheetParent.visibility = View.INVISIBLE
                    GifLoading2.visibility = View.VISIBLE
                }.bindLifeCycle(this)
                .subscribe({
                    if (it.code == 1) {
                        paperPerAnalysisInfor = it.data
                        //获取笔记及收藏状态
                        var quesIds = ""
                        val typeListSize = paperPerAnalysisInfor!!.TypeList.size
                        for (i in 0 until typeListSize) {
                            val quesListSize = paperPerAnalysisInfor!!.TypeList[i].QuesList.size
                            for (j in 0 until quesListSize) {
                                val quesId = paperPerAnalysisInfor!!.TypeList[i].QuesList[j].QuesID
                                if (quesIds.isEmpty()) {
                                    quesIds = quesId
                                } else {
                                    quesIds = "$quesIds|$quesId"
                                }
                            }
                        }

                        Handler().postDelayed({
                            showScoreView()
                            LoadPaperView()
                        }, 500)
                    } else {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 500)
                    }

                }, {
                    MyToast.showToast(it.message)
                    Handler().postDelayed({
                        finish()
                    }, 500)
                })
    }


    //加载我的得分相关信息
    private fun showScoreView() {
        val paperScoreRate = paperPerAnalysisInfor!!.PaperScoreRate
        val score = paperPerAnalysisInfor!!.Score
        val fullScore = paperPerAnalysisInfor!!.FullScore
        val averageScore = paperPerAnalysisInfor!!.AverageScore
        val highestScore = paperPerAnalysisInfor!!.HighestScore
        val duration = paperPerAnalysisInfor!!.Duration

        //屏蔽得分率
//        TvMyScoreRate.visibility = View.INVISIBLE
//        TvMyScoreRate.text = "我的得分(正确率$paperScoreRate%)"
        TvMyScoreRate.visibility = View.VISIBLE
        //显示我的得分
        if(score == "--"){
            TvMyScore.text = score
        }else{
            if (score != "0.0") {
                scoreSoundUtil!!.playSound(0)
            }
            if(score!!.contains(".")){
                val length = score!!.substring(score!!.lastIndexOf(".")+1).length
                if (length == 1) {
                    TvMyScore.showNumberWithAnimation(score!!.toFloat(), CountNumberView.FLOATREGEX_1);
                } else if (length == 2) {
                    TvMyScore.showNumberWithAnimation(score!!.toFloat(), CountNumberView.FLOATREGEX_2);
                }
            }else {
                TvMyScore.showNumberWithAnimation(score!!.toFloat(), CountNumberView.INTREGEX);
            }
        }
        TvMyScore.typeface = Typeface.createFromAsset(assets, "fonts/DIN Condensed Bold.ttf")
        TvSlash.typeface = Typeface.createFromAsset(assets, "fonts/DIN Condensed Bold.ttf")
        //显示试卷总分
        TvFullScore.text = fullScore
        TvFullScore.typeface = Typeface.createFromAsset(assets, "fonts/DIN Condensed Bold.ttf")
        //隐藏班级最高分和班级平均得分
        LlClassScore.visibility = View.INVISIBLE

        //显示用时
        val hours = LancooUtils.getHours(duration.toLong())
        val mins = LancooUtils.getMins(duration.toLong())
        val secs = LancooUtils.getSeconds(duration.toLong())
        if (duration == 0) {
            TvUseTime.text = "用时 " + "- -"
        } else {
            if (Integer.valueOf(hours) > 0) {
                val text1 = "<myfont color='#ffffff' size='" + DensityUtils.dp2px(this, 20f) + "'>" + hours + "'" + "</myfont>" +
                        "<myfont color='#ffffff' size='" + DensityUtils.dp2px(this, 16f) + "'>" + mins + "'" + "</myfont>" +
                        "<myfont color='#ffffff' size='" + DensityUtils.dp2px(this, 12f) + "'>" + secs + "''" + "</myfont>"
                val spanned1 = Html.fromHtml(text1, null, HtmlTagHandler("myfont"))
                TvUseTime.text = "用时 $spanned1"
            } else {
                val text1 = "<myfont color='#ffffff' size='" + DensityUtils.dp2px(this, 20f) + "'>" + mins + "'" + "</myfont>" +
                        "<myfont color='#ffffff' size='" + DensityUtils.dp2px(this, 12f) + "'>" + secs + "''" + "</myfont>"
                val spanned1 = Html.fromHtml(text1, null, HtmlTagHandler("myfont"))
                TvUseTime.text = "用时 $spanned1"
            }
        }
    }

    /**
     * 初始化界面控件的显示数据
     */
    private fun LoadPaperView() {

        //加载答题卡
        RvAnswerSheetParent.recycledViewPool.clear()
        RvAnswerSheetParent.setItemViewCacheSize(0)
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        RvAnswerSheetParent.layoutManager = manager

        val adapterParent = AibkAnalysisAnswerSheetParentAdapter(
                this, paperPerAnalysisInfor!!
        )
        RvAnswerSheetParent.adapter = adapterParent
        adapterParent.setClickParentListener(object : AibkAnalysisAnswerSheetParentAdapter.OnClickParentListener {
            override fun onClick(
                    index_A: Int,
                    index_B: Int,
                    index_C: Int
            ) {
                var sortIndex = paperPerAnalysisInfor!!.TypeList[index_A].QuesList[index_B].SortIndexList[index_C].SortIndex
                AibkPaperAnalysisActivity.launch(this@AibkAnalysisAnswerSheetActivity_1v1, paperId, paperName, "", sortIndex, paperPerAnalysisInfor!!)
            }

        })

        LlAnswerSheetParent.visibility = View.VISIBLE
        GifLoading2.visibility = View.GONE
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1) {
            if (resultCode == 100) {
//                paperPerAnalysisInfor = data?.getParcelableExtra<PaperPerAnalysisInfor>("PaperPerAnalysisInfor")
                val typeListPosition = data?.getIntExtra("TypeListPosition", 0)
                RecyclerViewScrollHelper.scrollToPosition(RvAnswerSheetParent, typeListPosition!!)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.BtnBack -> {
                finish()
            }
            R.id.BtnRefresh -> {
                Handler().postDelayed({
                    getpaperPerAnalysisInforAndRefresh()
                },100)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        scoreSoundUtil!!.stopSoundPool(1)
    }

    override fun onPause() {
        super.onPause()
        scoreSoundUtil!!.stopSoundPool(1)
    }

}